import system_setup
import device_info
import device_timing
from data_analysis import data_analysis_water, normal_data, alarm_data, data_analysis_hx100, data_subscription
from data_analysis.data_analysis_hx100 import hx100code
from data_analysis.data_analysis_hk_alarm import hk_alarm_sdk
from data_analysis.data_analysis import data_analysis,false_alarm_image
from hk import deploy_troops_for_defence, gate_control
from flask import Flask, request
import json
import upload_and_download
import car_plate_info
from flask_cors import CORS
from flask_apscheduler import APScheduler
import video_analysis.main_management_1
import video_analysis.main_management_2
import video_analysis.main_management_3
import video_analysis.main_management_4
import video_analysis.main_management_5
import threading
from uirls import web_socket
server = Flask(__name__)
CORS(server, resources=r'/*')
# 实例化 APScheduler
scheduler = APScheduler()

# ---------------------------------------------------系统设置------------------------------------------------
# 登录
@server.route("/gateway_api/system/login", methods=['post'])
def login():
    return system_setup.login()


# 用户新增
@server.route("/gateway_api/system/userAdd", methods=['post'])
def userAdd():
    return system_setup.userAdd()


# 用户编辑
@server.route("/gateway_api/system/userUpdate", methods=['post'])
def userUpdate():
    return system_setup.userUpdate()


# 用户删除
@server.route("/gateway_api/system/userDel", methods=['post'])
def userDel():
    return system_setup.userDel()


# 用户分页列表
@server.route("/gateway_api/system/userListPage", methods=['GET'])
def userListPage():
    return system_setup.userListPage()


# 解析token
@server.route("/gateway_api/system/getDecodeToken", methods=['post'])
def getDecodeToken():
    token = request.headers.get("Authorization", "")[7:]
    return system_setup.getDecodeToken(token)


# 获取网络信息
@server.route("/gateway_api/system/ethList", methods=['GET'])
def ethList():
    return system_setup.ethList()


# 配置网络信息
@server.route("/gateway_api/system/updateEth", methods=['post'])
def updateEth():
    return system_setup.updateEth()


# 获取系统信息
@server.route("/gateway_api/system/systemInfo", methods=['GET'])
def systemInfo():
    return system_setup.systemInfo()


# 获取系统状态
@server.route("/gateway_api/system/systemStateList", methods=['GET'])
def systemStateList():
    return system_setup.systemStateList()


# 获取gpu使用率
@server.route("/gateway_api/system/check_gpu_mem_usedRate", methods=['GET'])
def check_gpu_mem_usedRate():
    return system_setup.check_gpu_mem_usedRate()


# 获取主板序列号
@server.route("/gateway_api/system/get_main_board_info", methods=['GET'])
def get_main_board_info():
    return system_setup.get_main_board_info()


# 获取配置文件（数据库）
@server.route("/gateway_api/system/get_profile", methods=['GET'])
def get_profile():
    return system_setup.get_profile()


# 备份配置文件（数据库）
@server.route("/gateway_api/system/backup_profile", methods=['post'])
def backup_profile():
    return system_setup.backup_profile()


# 写入系统配置
@server.route("/gateway_api/system/set_system_config", methods=['post'])
def set_system_config():
    return system_setup.set_system_config()

# ---------------------------------------------------设备管理------------------------------------------------
# 设备新增
@server.route("/gateway_api/device/deviceAdd", methods=['post'])
def deviceAdd():
    return device_info.deviceAdd()


# 设备编辑
@server.route("/gateway_api/device/deviceUpdate", methods=['post'])
def deviceUpdeta():
    return device_info.deviceUpdate()


# 设备删除
@server.route("/gateway_api/device/deviceDel", methods=['post'])
def deviceDel():
    return device_info.deviceDel()


# 设备详情
@server.route("/gateway_api/device/deviceDetails", methods=['GET'])
def deviceDetails():
    return device_info.deviceDetails()


# 设备分页列表
@server.route("/gateway_api/device/deviceListPage", methods=['GET'])
def deviceListPage():
    return device_info.deviceListPage()


# 设备分类列表
@server.route("/gateway_api/device/deviceClassList", methods=['GET'])
def deviceClassList():
    return device_info.deviceClassList()


# 设备平时数据选项
@server.route("/gateway_api/device/device_normal_items", methods=['GET'])
def device_normal_items():
    return device_info.device_normal_items()


# 设备类型表
@server.route("/gateway_api/device/deviceTypeList", methods=['GET'])
def deviceTypeList():
    return device_info.deviceTypeList()


# 获取摄像头rtmp流
@server.route("/gateway_api/device/getRtmp", methods=['GET'])
def getRtmp():
    return device_info.getRtmp()


# 关闭摄像头rtmp流
@server.route("/gateway_api/device/closeRtmp", methods=['post'])
def closeRtmp():
    return device_info.closeRtmp()


# 设备产品列表
@server.route("/gateway_api/device/productList", methods=['GET'])
def productList():
    return device_info.productList()


# 视频设备列表
@server.route("/gateway_api/device/videoDeviceList", methods=['GET'])
def videoDeviceList():
    return device_info.video_device_List()


# 消防部件新增、编辑
@server.route("/gateway_api/device/component_add_update", methods=['post'])
def component_add_update():
    return device_info.component_add_update()


# 消防部件删除
@server.route("/gateway_api/device/component_del", methods=['post'])
def component_del():
    return device_info.component_del()


# 消防部件分页列表
@server.route("/gateway_api/device/component_list_page", methods=['GET'])
def component_list_page():
    return device_info.component_list_page()


# 消防部件类型列表
@server.route("/gateway_api/device/part_type_list", methods=['GET'])
def part_type_list():
    return device_info.part_type_list()


# 视频分析通道新增、编辑
@server.route("/gateway_api/device/camera_channel_add_update", methods=['post'])
def camera_channel_add_update():
    return device_info.camera_channel_add_update()


# 视频分析通道删除
@server.route("/gateway_api/device/camera_channel_del", methods=['post'])
def camera_channel_del():
    return device_info.camera_channel_del()


# 视频分析通道列表
@server.route("/gateway_api/device/camera_channel_list", methods=['GET'])
def camera_channel_list():
    return device_info.camera_channel_list()


# 获取局域网内onvif协议摄像头IP
@server.route("/gateway_api/device/get_onvif_camera_ip", methods=['GET'])
def get_onvif_camera_ip():
    return device_info.get_onvif_camera_ip()


# 组态应用新增
@server.route("/gateway_api/device/application_add", methods=['post'])
def application_add():
    return device_info.application_add()


# 组态应用更新
@server.route("/gateway_api/device/application_update", methods=['post'])
def application_update():
    return device_info.application_update()


# 组态应用删除
@server.route("/gateway_api/device/application_del", methods=['post'])
def application_del():
    return device_info.application_del()


# 组态应用分页列表
@server.route("/gateway_api/device/application_list_page", methods=['GET'])
def application_list_page():
    return device_info.application_list_page()


# 组态应用数据保存
@server.route("/gateway_api/device/application_data_preserve", methods=['post'])
def application_data_preserve():
    return device_info.application_data_preserve()


# 组态应用数据详情
@server.route("/gateway_api/device/application_data_details", methods=['GET'])
def application_data_details():
    return device_info.application_data_details()

# ---------------------------------------------------仪表盘数据------------------------------------------------

# 设备消息量(折线图)
@server.route("/gateway_api/data/all_data_count", methods=['GET'])
def all_data_count():
    return normal_data.all_data_count()


# 获取今日、当月消息量
@server.route("/gateway_api/data/all_data_day_month_count", methods=['GET'])
def all_data_day_month_count():
    return normal_data.all_data_day_month_count()


# 获取今日、当月报警量
@server.route("/gateway_api/data/day_month_alarm_count", methods=['GET'])
def day_month_alarm_count():
    return alarm_data.day_month_alarm_count()


# 统计设备数量
@server.route("/gateway_api/data/device_count", methods=['GET'])
def device_count():
    return device_info.device_count()


# 统计产品数量
@server.route("/gateway_api/data/product_count", methods=['GET'])
def product_count():
    return device_info.product_count()


# 最新告警列表（3条）
@server.route("/gateway_api/data/new_alarm_data_list", methods=['GET'])
def new_alarm_data_list():
    return alarm_data.new_alarm_data_list()


# 告警排名（前十）
@server.route("/gateway_api/data/alarm_ranking", methods=['GET'])
def alarm_ranking():
    return alarm_data.alarm_ranking()


# 告警统计（折线图）
@server.route("/gateway_api/data/all_alarm_data_count", methods=['GET'])
def all_alarm_data_count():
    return alarm_data.all_alarm_data_count()


# 今日报警数据统计
@server.route("/gateway_api/data/todayAlarmCount", methods=['GET'])
def today_alarm_count():
    return alarm_data.today_alarm_count()


# 今日报警数据统计
@server.route("/gateway_api/data/alarmListPage", methods=['GET'])
def alarmListPage():
    return alarm_data.alarmListPage()


# 报警日志详情
@server.route("/gateway_api/data/alarmDetails", methods=['GET'])
def alarmDetails():
    return alarm_data.alarmDetails()


# 报警日志处置
@server.route("/gateway_api/data/alarmHandle", methods=['post'])
def alarmHandle():
    return alarm_data.alarmHandle()


# 报警日志删除
@server.route("/gateway_api/data/alarm_log_del", methods=['post'])
def alarm_log_del():
    return alarm_data.alarm_log_del()


# ---------------------------------------------------数据解析------------------------------------------------

# 世成建筑消防用水解析
@server.route("/gateway_api/data/analysis/shi_cheng_dian_qi_water", methods=['post'])
def shi_cheng_dian_qi():
    return data_analysis_water.shi_cheng_dian_qi()


# 用户传输装置解析
@server.route("/gateway_api/data/analysis/data_analysis_hx100", methods=['post'])
def data_analysis_hx100():
    jsons = json.loads(request.data)
    return hx100code(jsons)


# 海康超脑数据解析（设备SDK）
@server.route("/gateway_api/data/analysis/hk_alarm", methods=['post'])
def hk_alarm():
    return hk_alarm_sdk()

# 数据解析
@server.route("/gateway_api/data/analysis/data_analysis", methods=['post'])
def data_analysis_s():
    return data_analysis()


# ---------------------------------------------------上传下载------------------------------------------------

# 设备导入模板下载
@server.route("/gateway_api/download/deviceTemplateDownload", methods=['GET'])
def deviceTemplateDownload():
    response = upload_and_download.deviceTemplateDownload()
    response.headers['Content-Type'] = "utf-8"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Content-Disposition"] = "attachment; filename=deviceTemplateDownload.xlsx"
    return response


# 设备导入
@server.route("/gateway_api/upload/deviceUpload", methods=['post'])
def deviceUpload():
    return upload_and_download.deviceUpload()


# 文件上传
@server.route("/gateway_api/upload/upload", methods=['post'])
def upload():
    return upload_and_download.upload()


# 上传许可
@server.route("/gateway_api/upload/upload_permit", methods=['post'])
def upload_permit():
    return upload_and_download.upload_permit()


# 上传解析文件
@server.route("/gateway_api/upload/upload_analysis", methods=['post'])
def upload_analysis():
    return upload_and_download.upload_analysis()


# 消防部件导入模板
@server.route("/gateway_api/download/component_template_download", methods=['GET'])
def component_template_download():
    response = upload_and_download.component_template_download()
    response.headers['Content-Type'] = "utf-8"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Content-Disposition"] = "attachment; filename=component_template_download.xlsx"
    return response


# 消防部件导入
@server.route("/gateway_api/upload/component_upload", methods=['post'])
def component_upload():
    return upload_and_download.component_upload()


# 下载驱动
@server.route("/gateway_api/upload/download_drive", methods=['post'])
def download_drive():
    return upload_and_download.download_drive()


# 上传配置文件（数据库）
@server.route("/gateway_api/upload/upload_profile", methods=['post'])
def upload_profile():
    return upload_and_download.upload_profile()


# 上传logo
@server.route("/gateway_api/upload/upload_logo", methods=['post'])
def upload_logo():
    return upload_and_download.upload_logo()

# ---------------------------------------------------道闸管理------------------------------------------------

# 车牌新增、更新
@server.route("/gateway_api/car_plate_add_update", methods=['post'])
def car_plate_add_update():
    return car_plate_info.car_plate_add_update()


# 车牌分页列表
@server.route("/gateway_api/car_plate_list_page", methods=['get'])
def car_plate_list_page():
    return car_plate_info.car_plate_list_page()


# 车牌删除
@server.route("/gateway_api/car_plate_del", methods=['post'])
def car_plate_del():
    return car_plate_info.car_plate_del()


# 海康道闸布防
@server.route("/gateway_api/place_troops_on_garrison_duty", methods=['post'])
def place_troops_on_garrison_duty():
    return deploy_troops_for_defence.place_troops_on_garrison_duty()


# 海康道闸撤防
@server.route("/gateway_api/withdraw_garrison", methods=['post'])
def withdraw_garrison():
    return deploy_troops_for_defence.withdraw_garrison()


# 海康开闸
@server.route("/gateway_api/cate_control", methods=['post'])
def cate_control():
    return gate_control.cate_control()


# ---------------------------------------------------物联网------------------------------------------------
# 订阅地址新增
@server.route("/gateway_api/data/setSubscriptionAddress", methods=['post'])
def setSubscriptionAddress():
    return data_subscription.setSubscriptionAddress()


# 订阅地址删除
@server.route("/gateway_api/data/delSubscriptionAddress", methods=['post'])
def delSubscriptionAddress():
    return data_subscription.delSubscriptionAddress()


# 更新订阅地址状态
@server.route("/gateway_api/data/updateSubscriptionAddressState", methods=['post'])
def updateSubscriptionAddressState():
    return data_subscription.updateSubscriptionAddressState()


# 订阅地址列表
@server.route("/gateway_api/data/subscriptionAddressList", methods=['get'])
def subscriptionAddressList():
    return data_subscription.subscriptionAddressList()


# 调试短信、语音通知
@server.route("/gateway_api/data/data_push_test", methods=['post'])
def data_push_test():
    return data_subscription.data_push_test()


# 通知新增
@server.route("/gateway_api/device/communicationAdd", methods=['post'])
def communicationAdd():
    return device_info.communicationAdd()


# 通知编辑
@server.route("/gateway_api/device/communicationUpdate", methods=['post'])
def communicationUpdate():
    return device_info.communicationUpdate()


# 通知删除
@server.route("/gateway_api/device/communicationDel", methods=['post'])
def communicationDel():
    return device_info.communicationDel()


# 通知配置分页列表
@server.route("/gateway_api/device/communication_list_page", methods=['get'])
def communication_list_page():
    return device_info.communication_list_page()


# 通讯记录分页列表
@server.route("/gateway_api/device/communication_record_list_page", methods=['get'])
def communication_record_list_page():
    return device_info.communication_record_list_page()


# ---------------------------------------------------视频分析------------------------------------------------


# 手动停止算法任务
@server.route('/gateway_api/docker_stop', methods=['POST'])
def docker_stop():
    return video_analysis.main_management_1.docker_stop_manual()


# 手动启动算法任务
@server.route('/gateway_api/docker_start', methods=['POST'])
def docker_start():
    return video_analysis.main_management_1.docker_start_manual()


# 停止并删除算法任务
@server.route('/gateway_api/delete_stop', methods=['POST'])
def delete_stop():
    return video_analysis.main_management_1.delete_stop()


# 判定暂存参数或创建算法任务，绑定 “确定” 键
@server.route('/gateway_api/judge_operation', methods=['POST'])
def judge_operation():
    return video_analysis.main_management_3.judge_operation()


# 查询任务列表
@server.route('/gateway_api/query_args', methods=['POST', 'GET'])
def query_args():
    return video_analysis.main_management_3.query_args()


# 获取摄像头实时图片（含自动保存至已存在的任务中）
@server.route('/gateway_api/get_base64img', methods=['POST'])
def get_base64img():
    return video_analysis.main_management_1.get_base64img()


# 获取算法列表
@server.route('/gateway_api/algorithm_list', methods=['POST'])
def algorithm_list():
    return video_analysis.main_management_1.algorithm_list()


# 获取物体对象列表
@server.route('/gateway_api/object_list', methods=['POST'])
def object_list():
    return video_analysis.main_management_2.object_list()


# 获取算法商城列表
@server.route('/gateway_api/algorithm_shop_list', methods=['GET'])
def algorithm_shop_list():
    return video_analysis.main_management_5.algorithm_shop_list()


# 添加算法至个人账号算法库
@server.route('/gateway_api/authorization', methods=['POST'])
def authorization():
    return video_analysis.main_management_5.authorization()


# 更新算法状态时间
@server.route('/gateway_api/normal_update_time', methods=['POST'])
def normal_update_time():
    return video_analysis.main_management_5.normal_update_time()


# 校验模型是否下载完成
@server.route('/gateway_api/model_file', methods=['POST'])
def model_file():
    return video_analysis.main_management_5.model_file()


# 误报图片保存上传
@server.route('/gateway_api/false_alarm_image', methods=['POST'])
def falseAlarmImage():
    return false_alarm_image()


# 设置清理报警图片时间
@server.route('/gateway_api/set_clean_date', methods=['POST'])
def set_clean_date():
    return video_analysis.main_management_5.set_clean_date()


# 查询清理日期
@server.route('/gateway_api/query_clean_date', methods=['POST'])
def query_clean_date():
    return video_analysis.main_management_5.query_clean_date()


# 查询算法运行日志
@server.route('/gateway_api/send_docker_operation_log', methods=['POST'])
def send_docker_operation_log():
    return video_analysis.main_management_1.send_docker_operation_log()


# 升级算法
@server.route('/gateway_api/update_algorithm', methods=['POST'])
def update_algorithm():
    return video_analysis.main_management_5.update_algorithm()


# ---------------------------------------------------定时任务------------------------------------------------


# 定时修改设备离线状态(每十分钟执行一次)
@scheduler.task('interval', id='update_Off', minutes=10)
def update_Off():
    device_timing.update_Off()


# 视频设备更新在线时间(每小时执行一次)
@scheduler.task('interval', id='camera_normal_update_time', hours=1)
def camera_normal_update_time():
    device_timing.camera_normal_update_time()


# 检测算法是否还存活(每60秒执行一次)
@scheduler.task('interval', id='detection_algorithm_normal_update_time', seconds=60)
def detection_algorithm_normal_update_time():
    video_analysis.main_management_5.detection_algorithm_normal_update_time()


# 算法任务自动定时器(每分钟执行一次)
@scheduler.task('interval', id='timer', minutes=1)
def timer():
    return video_analysis.main_management_4.timer()


# 清理过时报警图片(每天执行一次)
@scheduler.task('interval', id='clean_alarm_pic', days=1)
def clean_alarm_pic():
    video_analysis.main_management_5.clean_alarm_pic()


# 清理摄像头实时图片缓存(每周执行一次)
@scheduler.task('interval', id='clean_rtsp_pic', days=7)
def clean_rtsp_pic():
    return video_analysis.main_management_1.clean_rtsp_pic()


# 检查算法更新(每天执行一次)
@scheduler.task('interval', id='check_update_algorithm', days=1)
def check_update_algorithm():
    return video_analysis.main_management_5.check_update_algorithm()


# -----------------------------------------------------------------------------------------------------------


# web_socket服务
def w_s():
    web_socket.application.listen(9016)
    web_socket.tornado.ioloop.IOLoop.instance().start()


# api服务
def api_server():
    server.run(host='0.0.0.0', debug=False, port=5001, threaded=True)


if __name__ == '__main__':
    # 启动定时任务
    scheduler.start()
    thread1 = threading.Thread(name="t1",target=w_s)
    thread2 = threading.Thread(name="t2",target=api_server)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
